import { createRouter, createWebHistory, type RouteRecordRaw, type Router } from 'vue-router'

//静态路由
const routes: Array<RouteRecordRaw> = [{
    path: '/',
    name: 'index',
    component: () => import('@/views/index.vue')
}, {
    path: '/about',
    name: 'about',
    component: () => import('@/views/about.vue')
}, {
    //404
    path: '/404',
    name: '404',
    component: () => import('@/views/404.vue')
}]

const router = createRouter({
    history: createWebHistory(),
    routes,
    scrollBehavior: (_to, _from, savedPosition) => {
        if (savedPosition) {
            return savedPosition
        }
    }
})

// 防止无限循环
let isAddingRoute = false
router.beforeEach(async (to, from, next) => {
    if (to.matched.length === 0 && !isAddingRoute) {
        // 如果没有匹配到路由，并且不在添加路由的过程中
        isAddingRoute = true
        // 尝试添加路由（这里假设你有一个方法来做这个）
        await addDynamicRoute(to.path)
        isAddingRoute = false
        // 重新尝试导航
        next({ ...to, replace: true })
    } else if (to.matched.length === 0) {
        // 如果还是没有匹配到路由，重定向到 404
        next({ name: '404', replace: true })
    } else {
        // 正常情况，继续导航
        next()
    }
})

// 添加动态路由的函数
async function addDynamicRoute(path: string) {
    // 这里应该是你的逻辑来动态添加路由
    // 例如：
    const dynamicRoutes = await fetchDynamicRoutes() // 假设这是一个异步函数来获取动态路由
    dynamicRoutes.forEach(route => router.addRoute(route))
}
// 模拟获取动态路由
async function fetchDynamicRoutes(): Promise<RouteRecordRaw[]> {
    // 这里应该是你的实际逻辑来获取动态路由
    // 这只是一个示例
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve([
                {
                    path: '/dynamic',
                    name: 'dynamic',
                    component: () => import('@/views/Dynamic.vue')
                },
                {
                    path: '/dynamic2',
                    name: 'dynamic2',
                    component: () => import('@/views/Dynamic2.vue')
                }
            ])
        }, 1000)
    })
}

// 初始化路由
function initRouter(): Router {
    return router
}
export { initRouter }